using Microsoft.IdentityModel.Tokens;
using PetAdoptApi.Entity;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace PetAdoptApi.Services.Auth;

public class TokenService
{
    private readonly int _expireMinutes;
    private readonly SymmetricSecurityKey _key;
    private readonly string _issuer;

    public TokenService(IConfiguration configuration)
    {
        _expireMinutes = Convert.ToInt32(configuration["Jwt:ExpireMinutes"]);
        _key = new(Encoding.UTF8.GetBytes(configuration["Jwt:Key"]!));
        _issuer = configuration["Jwt:Issuer"]!;
    }

    public string GenJwt(IEnumerable<Claim>? additionalClaims = null)
    {
        var credential = new SigningCredentials(_key, SecurityAlgorithms.HmacSha256);
        var claims = new List<Claim> { 
            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
        };
        if (additionalClaims?.Any() == true) claims.AddRange(additionalClaims);
        var token = new JwtSecurityToken(issuer: _issuer, audience: "*",
            claims: claims, expires: DateTime.Now.AddMinutes(_expireMinutes),
            signingCredentials: credential
            );
        return new JwtSecurityTokenHandler().WriteToken(token);
    }

    public string GenJwt(User user,IEnumerable<Claim>? additionalClaims = null)
    {
        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.NameIdentifier,user.Id.ToString()),
            new Claim(ClaimTypes.Name,user.Name)
        };
        if (additionalClaims?.Any() == true) claims.AddRange(additionalClaims);
        return GenJwt(claims);
    }

    //public User? ParseJwt(string jwt)
    //{

    //}
}
